# PCA9685 PWM 伺服/LED控制器库的简单演示
# 这将重复地将通道0从最小位置移动到最大位置。
# Author: Tony DiCola
# License: Public Domain
from __future__ import division
import time

# Import the PCA9685 module.
import Adafruit_PCA9685

# 取消注释以启用调试输出。
# import logging
# logging.basicConfig(level=logging.DEBUG)

# 使用默认地址(0x40)初始化PCA9685。
pwm = Adafruit_PCA9685.PCA9685()

# 或者指定不同的地址和/或总线:
# pwm = Adafruit_PCA9685.PCA9685(address=0x41, busnum=2)

# 配置最小和最大伺服脉冲长度
servo_min = 150  # 最小脉冲长度出不了4096，原来150
servo_max = 600  # 最大脉冲长度4096，原来600


# 辅助功能，使伺服脉冲宽度的设定更简单。
def set_servo_pulse(channel, pulse):
    pulse_length = 1000000  # 1,000,000 us per second
    pulse_length //= 60  # 60 Hz
    print('{0}us per period'.format(pulse_length))
    pulse_length //= 4096  # 12位分辨率
    print('{0}us per bit'.format(pulse_length))
    pulse *= 1000
    pulse //= pulse_length
    pwm.set_pwm(channel, 0, pulse)


# 频率设置为60hz，适合操作
pwm.set_pwm_freq(60)

print('每次移动所有电机，按Ctrl-C退出…')
while True:
    # 在两个极端之间移动伺服电机。
    pwm.set_pwm(0, 0, servo_min)
    time.sleep(1)
    pwm.set_pwm(0, 0, servo_max)
    time.sleep(1)

    pwm.set_pwm(1, 0, servo_min)
    time.sleep(1)
    pwm.set_pwm(1, 0, servo_max)
    time.sleep(1)

    pwm.set_pwm(2, 0, servo_min)
    time.sleep(1)
    pwm.set_pwm(2, 0, servo_max)
    time.sleep(1)

    pwm.set_pwm(3, 0, servo_min)
    time.sleep(1)
    pwm.set_pwm(3, 0, servo_max)
    time.sleep(1)

    pwm.set_pwm(4, 0, servo_min)
    time.sleep(1)
    pwm.set_pwm(4, 0, servo_max)
    time.sleep(1)

    pwm.set_pwm(5, 0, servo_min)
    time.sleep(1)
    pwm.set_pwm(5, 0, servo_max)
    time.sleep(1)

    pwm.set_pwm(10, 0, servo_min)
    time.sleep(1)
    pwm.set_pwm(10, 0, servo_max)
    time.sleep(1)

    pwm.set_pwm(11, 0, servo_min)
    time.sleep(1)
    pwm.set_pwm(11, 0, servo_max)
    time.sleep(1)

    pwm.set_pwm(12, 0, servo_min)
    time.sleep(1)
    pwm.set_pwm(12, 0, servo_max)
    time.sleep(1)

    pwm.set_pwm(13, 0, servo_min)
    time.sleep(1)
    pwm.set_pwm(13, 0, servo_max)
    time.sleep(1)

    pwm.set_pwm(14, 0, servo_min)
    time.sleep(1)
    pwm.set_pwm(14, 0, servo_max)
    time.sleep(1)

    pwm.set_pwm(15, 0, servo_min)
    time.sleep(1)
    pwm.set_pwm(15, 0, servo_max)
    time.sleep(1)
